/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package util

import (
	"prim-server/common"
	"time"

	"github.com/astaxie/beego"
	"github.com/dgrijalva/jwt-go"
	"github.com/pkg/errors"
)

func GetJWTToken(sessionId, userId string, expireTime time.Time) (string, error) {
	claims := &common.Claims{
		SessionId: sessionId,
		StandardClaims: jwt.StandardClaims{
			Id:        userId,
			ExpiresAt: expireTime.Unix(),
		},
	}
	key := beego.AppConfig.String("jwtkey")
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(key))
	return token, err
}

func ParseToken(token string) (*common.Claims, error) {
	key := beego.AppConfig.String("jwtkey")
	tokenClaims, err := jwt.ParseWithClaims(token, &common.Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if err != nil {
		return nil, err
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*common.Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, errors.New("Invalid token")
}
